package netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/6 19:24
 */
//单线程读取
public class SocketChannelDemo {
    public static void main(String[] args) throws Exception {
        InetSocketAddress inetAddress = new InetSocketAddress(7000);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(inetAddress);

        SocketChannel socketChannel = serverSocketChannel.accept();

        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(3);
        buffers[1] = ByteBuffer.allocate(5);

        while(true){
            long i = socketChannel.read(buffers,0,buffers.length);

            Arrays.stream(buffers).map(buffer -> "pos:"+buffer.position()+",limit:"+buffer.limit()).forEach(System.out::println);

            if(i==-1){
                break;
            }

            Arrays.stream(buffers).forEach(buffer -> buffer.clear());
        }

    }
}
